Mapped Types Modifiers
from Mapped Types
TypeScript v2.8
揺れがある
「Mapped Type Modifiers」とか ref
「Mapping Modifiers」とか ref
「Modifier Type」とか ref
readonlyや?のことをmodifier(修飾子)と呼んでて、
それをMapped Typesの定義時に、付与したり、除去したりできるので
「Mapped Types Modifiers」の様に呼んだりする
以下の様に、constraint typeにkeyofが付いている時に使える
[]の中でkeyofを付けている
code:ts
type A<T> = { P in keyof T: string };
extendsの中で、keyofの制約がある
code:ts
type Pick<T, K extends keyof T> = { P in K: TP; }
readonlyや?を付ける
例えば、全てのpropertyに?を付けるPartial<R>
code:ts
type Partial<T> = {
P in keyof T?: TP;
};
こうなる
code:ts
type A = Partial<{ a: number; b: number }>;
// 以下と同じ
// type A = {
// a?: number | undefined;
// b?: number | undefined;
// };
ただの[..]?じゃなくて、[..]+?とも書けるが、全く同じ意味になる
なんで用意しているんだろう #??
?を取り除く
-を付ける
例えば、全てのpropertyを必須にするRequired<T>
code:ts
type Required<T> = {
P in keyof T-?: TP;
};
こうなる
code:ts
type A = Required<{ a?: number; b?: number | undefined }>;
// 以下と同じ
// type A = { a: number; b: number; };
readonlyを取り除く
-を付ける
code:ts
type Mutable<T> = {
-readonly P in keyof T: TP;
};
参考
Mapped Typesのあれこれ